const {cache} = require('../config/defaultConfig');

function refreshRes(stats, res) {
    const {maxAge, expires, cacheControl, lastModified, etag} = cache;

    if(expires){
        res.setHeader("Expires", (new Date(new Date()+ maxAge*1000 )).toUTCString());
    }

    if(cacheControl){
        res.setHeader("Cache-Control", `public, max-age=${maxAge}`);
    }

    if(lastModified){
        res.setHeader("last-Modified", stats.mtime.toUTCString());
    }

    if(etag){
        res.setHeader("Etag", `${stats.size}-${stats.mtime}`);
    }

}

module.exports = (stats, req, res)=>{
    refreshRes(stats, res);

    const lastModified = req.headers['if-modified-since'];
    const etag = req.headers['if-none-match'];

    if(!lastModified && !etag){
        return false;
    }

    if(lastModified && lastModified !== res.getHeader('lastModified')){
        return false;
    }

    if(etag && etag !== res.getHeader('Etag') ){
        return false;
    }

    return true;

};
